<?php

namespace common\models;

use Yii;

/**
 * 资产包团队收益分配表
 * This is the model class for table "package_initiation_income".
 *
 * @property integer $id
 * @property string $package_id
 * @property string $stage
 * @property string $profit
 * @property string $created_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 */
class PackageInitiationIncome extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_initiation_income';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id', 'stage'], 'required'],
            [['package_id', 'lock_user'], 'integer'],
            [['profit'], 'string'],
            [['created_at'], 'safe'],
            [['stage', 'lock_timestamp'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'package_id' => '资产包',
            'stage' => '阶段',
            'profit' => '成员及分配比例',
            'created_at' => '创建时间',
            'lock_user' => '上锁用户',
            'lock_timestamp' => '上锁时间',
        ];
    }

    /**
     * 获取列表
     * @param $where 条件
     * @return array
     */
    public function getList($where)
    {
        $queryBulider = new yii\db\Query();
        $list = $queryBulider
            ->select([])
            ->from($this->tableName())
            ->where($where)
            ->orderBy(['id' => SORT_ASC])
            ->indexBy('id')
            ->all();

        return $list;
    }


    /**
     * @param $id 主键
     * @param $package_id 资产包id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 资类包修改日志module
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public function setUpdateLog($id, $package_id, $changedAttributes, $userId, $module, $type)
    {
        $model = self::findOne((int)$id);
        $package = Package::findOne($package_id);
        if ($model === null || $package === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        $attributeLabels = self::attributeLabels();
        $intAttributeLabels = ['package_id', 'lock_user'];
        $userInfo = (new UserModel())->getDepartmentUsersList(['user.id' => $userId]);
        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'lock_user':
                                    if ($value > 0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default;
                            }
                        }
                        if ($attributeLabels[$key] != 'ID') {
                            $log .= "{$attributeLabels[$key]}：{$value}\n";
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    return array('state' => false, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '修改为';
                    //$log = '修改ID：' . $id . ',';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'lock_user':
                                    if ($value > 0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default;
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
            default;
        }

        try {
            $time = date('Y-m-d H:i:s');
            $packageUpdateLog = new PackageUpdateLog();
            $module_title_array = $packageUpdateLog->getModuleArrayTitle();
            $packageUpdateLog->package_id = $package_id;
            $packageUpdateLog->module = $module_title_array[$module];
            $packageUpdateLog->created_at = $time;
            $packageUpdateLog->user_id = $userId;
            $packageUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');

            $re1 = $packageUpdateLog->save();
            if (!$re1) {
                throw new Exception('资产包团队收益分配添加日志失败');
            }

            return array('state' => true, 'msg' => '添加资产包修改日志成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
